import { _decorator, Button, Label, Tween, tween, UITransform } from 'cc';
import { AudioManager } from '../../../frame/component/audio-manager';
import { BasePopUp } from '../../../frame/component/ui.pop-up';
import { ClientAPI } from '../../api/client.api';
import GameAssets from '../../manager/game.assets';
import GameManager from '../../manager/game.manager';
import type { Popup } from '../page/popup';
const { ccclass, property } = _decorator;

@ccclass('FruitDiamond')
export class FruitDiamond extends BasePopUp<typeof Popup, number> {
	protected default_return: number;

	private light: UITransform;
	private lbl_diamond: Label;
	private icon_diamond: UITransform;

	private diamond: number;

	protected initAfterOnLoad(){
		this.light = this.node.getChildByName('light').getComponent(UITransform);
		this.lbl_diamond = this.node.getChildByName('lbl-diamond').getComponent(Label);
		this.icon_diamond = this.node.getChildByName('icon-diamond').getComponent(UITransform);

		this.renderLocalUI();
	}

	protected _click_event_: { [name: string]: (this: FruitDiamond, button: Button) => void; } = {
		reap(btn){
			btn.interactable = false;
			this.exit(false).then(()=>btn.interactable = true);
		},
		video(btn){
			btn.interactable = false;
			this.exit(true).then(()=>btn.interactable = true);
		},
	}

	public onShow(diamond: number){
		this.diamond = diamond;

		this.lbl_diamond.string = '+ ' + diamond;

		BasePopUp.jelly_enter(this.node);
		this.enter();

		AudioManager.playEffect(AudioManager.EAudio.BGM_DIAMOND);
	}

	private enter(){
		Tween.stopAllByTarget(this.light.node);

		this.light.node.angle = 0;
		tween(this.light.node)
		.set({angle: 0}).to(5, {angle: -360}).union()
		.repeatForever().start();
	}

	private async exit(video: boolean){
		let diamond = this.diamond;
		if(video){
			diamond = diamond * 2;
			await ClientAPI.AD('incentive');
		}

		if(diamond){
			GameManager.changeDiamond(diamond);
			GameManager.reapDiamond(diamond, this.icon_diamond.node.worldPosition);
		}

		await BasePopUp.jelly_leave(this.node);
		this.close(diamond);
		Tween.stopAllByTarget(this.light.node);
	}

	private renderLocalUI(){
		(<const>[
			['lbl-head', 16],
			['lbl-video', 41],
			['reap', 60],
		]).forEach(([name, idx])=>{
			this.node.getChildByName(name).getComponent(Label).string = GameAssets.getLangText(idx);
		});
	}
}

